package com.sunny.netty.handler;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;

/**
 * 换行符解析器客户端
 *
 * @author sunny
 * @date 2018/12/4
 */
public class LineBasedFrameDecoderClientHandler extends ChannelHandlerAdapter {
    private byte[] req;
    private int counter;

    public LineBasedFrameDecoderClientHandler() {
        this.req = ("QUERY TIME ORDER\n".getBytes());
    }

    /**
     * 处理一些异常情况
     *
     * @param ctx
     * @param cause
     * @author sunny
     * @date 2018/12/4
     * @return void
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        //不重写将会看到堆栈信息以及资源无法关闭
        System.out.println("释放资源：" + cause.getMessage());
        ctx.close();
    }

    /**
     * 发送客户端信息
     *
     * @param ctx
     * @author sunny
     * @date 2018/12/4
     * @return void
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        //推送消息
        ByteBuf message = null;
        for (int i = 0; i < 100; i++) {
            message = Unpooled.buffer(req.length);
            message.writeBytes(req);
            ctx.writeAndFlush(message);
        }
    }

    /**
     * 接收服务器数据
     *
     * @param ctx
     * @param msg
     * @author sunny
     * @date 2018/12/4
     * @return void
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        String body = (String) msg;
        System.out.println("client 接收到的消息：" + body + "；当前统计：" + ++counter);
    }

    public static void connect(String host, int port) {
        NioEventLoopGroup group = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        ChannelFuture future = null;

        try {
            bootstrap.group(group).channel(NioSocketChannel.class)
                    //不延迟，消息立即推送
                    .option(ChannelOption.TCP_NODELAY, true)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            //添加一个基于行的解码器 解决粘包拆包的问题 它是根据\n或者\r\n判断的
                            socketChannel.pipeline().addLast(new LineBasedFrameDecoder(1024));

                            socketChannel.pipeline().addLast(new StringDecoder());
                            socketChannel.pipeline().addLast(new LineBasedFrameDecoderClientHandler());
                        }
                    });

            //发起异步请求
            future = bootstrap.connect(host, port).sync();
            //等待客户端链路关闭
            future.channel().closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            group.shutdownGracefully();
        }
    }

    public static void main(String[] args) {
        LineBasedFrameDecoderClientHandler.connect("127.0.0.1", 4040);
    }
}
